<template>
  <el-container direction="vertical">
    <el-header>
      <el-row type="flex" align="middle">
        <el-col :span="12">
          <h2>学生详细信息</h2>
        </el-col>
        <el-col :span="12" style="text-align: right">
          <el-button @click="goBack" icon="el-icon-back" size="small">返回</el-button>
        </el-col>
      </el-row>
    </el-header>

    <!-- 加载中状态显示 -->
    <el-row v-if="loading" type="flex" justify="center" align="middle" style="height: 400px;">
      <el-col :span="24" style="text-align: center">
        <el-spinner></el-spinner>
        <p>数据加载中...</p>
      </el-col>
    </el-row>

    <el-container v-else>
      <el-main>
        <!-- 学生基本信息卡片 -->
        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-user"></i> 基本信息</span>
          </div>

          <el-row :gutter="20">
            <el-col :xs="24" :md="12">
              <el-descriptions border>
                <el-descriptions-item label="姓名">{{ student.studentName }}</el-descriptions-item>
                <el-descriptions-item label="学号">{{ student.studentId }}</el-descriptions-item>
                <el-descriptions-item label="班级">{{ student.className }}</el-descriptions-item>
                <el-descriptions-item label="专业">{{ student.major }}</el-descriptions-item>
                <el-descriptions-item label="入学年份">{{ student.enrollmentYear }}</el-descriptions-item>
                <el-descriptions-item label="总成绩">
                  <span class="total-score">{{ student.totalScore }}</span>
                </el-descriptions-item>
              </el-descriptions>
            </el-col>
            <el-col :xs="24" :md="12">
              <!-- 出勤率饼图 -->
              <div ref="attendanceRateChart" style="height: 250px;"></div>
            </el-col>
          </el-row>
        </el-card>

        <!-- 出勤记录表格 -->
        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-date"></i> 出勤记录</span>
            <el-select v-model="selectedCourse" placeholder="选择课程" style="float: right; width: 200px" size="small" @change="filterAttendanceRecords">
              <el-option label="全部课程" value=""></el-option>
              <el-option v-for="course in courseOptions" :key="course.value" :label="course.label" :value="course.value"></el-option>
            </el-select>
          </div>

          <el-table :data="filteredAttendanceRecords" style="width: 100%" :max-height="400" border stripe>
            <el-table-column prop="date" label="日期" width="100"></el-table-column>
            <el-table-column prop="courseName" label="课程名称"></el-table-column>
            <el-table-column prop="timeSlot" label="课程时间" width="150"></el-table-column>
            <el-table-column prop="classroom" label="教室" width="120"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === '出勤' ? 'success' : 'danger'">
                  {{ scope.row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="note" label="备注"></el-table-column>
          </el-table>

          <div class="pagination-container">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalAttendanceRecords">
            </el-pagination>
          </div>
        </el-card>

        <!-- 成绩记录 -->
        <el-card shadow="hover" class="mb-4">
          <div slot="header" class="clearfix">
            <span><i class="el-icon-notebook-1"></i> 科目成绩</span>
          </div>

          <!-- 成绩柱状图 -->
          <div ref="scoreChart" style="height: 350px;"></div>
        </el-card>
      </el-main>
    </el-container>
  </el-container>
</template>

<script>
import * as echarts from 'echarts/core';
import { PieChart, BarChart } from 'echarts/charts';
import { TitleComponent, TooltipComponent, LegendComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';

echarts.use([PieChart, BarChart, TitleComponent, TooltipComponent, LegendComponent, GridComponent, CanvasRenderer]);

export default {
  name: 'StudentDetail',
  data() {
    return {
      loading: true,
      studentId: this.$route.params.studentId,
      student: {},
      attendanceRecords: [],
      filteredAttendanceRecords: [],
      courseOptions: [],
      selectedCourse: '',
      currentPage: 1,
      pageSize: 10,
      totalAttendanceRecords: 0,
      scores: []
    };
  },
  mounted() {
    this.fetchStudentData();
  },
  methods: {
    async fetchStudentData() {
      try {
        this.loading = true;
        console.log('获取学生ID为', this.studentId, '的详细信息');
        
        // 使用模拟数据进行开发测试
        this.useMockData();
        
        // 当后端API准备好后，可以使用下面的代码代替模拟数据
        /*
        // 获取学生基本信息
        const studentRes = await this.$request.get(`/api/students/${this.studentId}`);
        this.student = studentRes.data;
        
        // 获取出勤记录
        const attendanceRes = await this.$request.get(`/api/students/${this.studentId}/attendance`);
        this.attendanceRecords = attendanceRes.data;
        this.totalAttendanceRecords = this.attendanceRecords.length;
        this.filteredAttendanceRecords = this.attendanceRecords.slice(0, this.pageSize);
        
        // 获取课程列表
        const coursesRes = await this.$request.get(`/api/courses`);
        this.courseOptions = coursesRes.data.map(course => ({
          value: course.courseId,
          label: course.courseName
        }));
        
        // 获取成绩记录
        const scoresRes = await this.$request.get(`/api/students/${this.studentId}/scores`);
        this.scores = scoresRes.data;
        */
        
      } catch (error) {
        console.error('获取学生数据失败:', error);
        this.$message.error('获取学生数据失败，请稍后重试');
      } finally {
        this.loading = false;
        this.$nextTick(() => {
          this.initCharts();
        });
      }
    },
    
    useMockData() {
      // 模拟学生基本信息
      this.student = {
        studentId: this.studentId || '20210001',
        studentName: '张三',
        className: '计算机科学2班',
        major: '计算机科学与技术',
        enrollmentYear: '2021',
        totalScore: 87.5,
        attendanceRate: 92.5,
        absentCount: 6,
        presentCount: 74
      };
      
      // 模拟出勤记录
      const generateAttendanceRecords = () => {
        const records = [];
        const courses = ['高等数学', '数据结构', '操作系统', '计算机网络', '编译原理'];
        const classrooms = ['教学楼A-101', '教学楼B-203', '教学楼C-305', '实验楼D-202'];
        const timeSlots = ['08:00-09:50', '10:10-12:00', '14:00-15:50', '16:10-18:00'];
        const statuses = ['出勤', '缺勤'];
        
        // 生成80条记录
        for (let i = 0; i < 80; i++) {
          // 生成过去90天内的随机日期
          const date = new Date();
          date.setDate(date.getDate() - Math.floor(Math.random() * 90));
          const formattedDate = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
          
          const courseName = courses[Math.floor(Math.random() * courses.length)];
          const status = Math.random() > 0.2 ? '出勤' : '缺勤'; // 80%出勤率
          
          records.push({
            id: i + 1,
            date: formattedDate,
            courseName: courseName,
            courseId: `C${String(courses.indexOf(courseName) + 1).padStart(4, '0')}`,
            timeSlot: timeSlots[Math.floor(Math.random() * timeSlots.length)],
            classroom: classrooms[Math.floor(Math.random() * classrooms.length)],
            status: status,
            note: status === '缺勤' ? ['病假', '事假', '无故缺勤'][Math.floor(Math.random() * 3)] : ''
          });
        }
        
        // 按日期排序，最近的日期在前
        return records.sort((a, b) => new Date(b.date) - new Date(a.date));
      };
      
      this.attendanceRecords = generateAttendanceRecords();
      this.totalAttendanceRecords = this.attendanceRecords.length;
      this.filteredAttendanceRecords = this.attendanceRecords.slice(0, this.pageSize);
      
      // 模拟课程选项
      this.courseOptions = [
        { value: 'C0001', label: '高等数学' },
        { value: 'C0002', label: '数据结构' },
        { value: 'C0003', label: '操作系统' },
        { value: 'C0004', label: '计算机网络' },
        { value: 'C0005', label: '编译原理' }
      ];
      
      // 模拟成绩数据
      this.scores = [
        { courseId: 'C0001', courseName: '高等数学', score: 85 },
        { courseId: 'C0002', courseName: '数据结构', score: 92 },
        { courseId: 'C0003', courseName: '操作系统', score: 78 },
        { courseId: 'C0004', courseName: '计算机网络', score: 88 },
        { courseId: 'C0005', courseName: '编译原理', score: 81 }
      ];
    },
    
    initCharts() {
      this.initAttendanceRateChart();
      this.initScoreChart();
    },
    
    initAttendanceRateChart() {
      const chartDom = this.$refs.attendanceRateChart;
      if (!chartDom) return;
      
      const myChart = echarts.init(chartDom);
      
      const option = {
        title: {
          text: '出勤率统计',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b}: {c} ({d}%)'
        },
        legend: {
          bottom: '5%',
          left: 'center'
        },
        series: [
          {
            name: '出勤情况',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '18',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: this.student.presentCount || 0, name: '出勤', itemStyle: { color: '#4CAF50' } },
              { value: this.student.absentCount || 0, name: '缺勤', itemStyle: { color: '#F44336' } }
            ]
          }
        ]
      };
      
      option && myChart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => {
        myChart.resize();
      });
    },
    
    initScoreChart() {
      const chartDom = this.$refs.scoreChart;
      if (!chartDom) return;
      
      const myChart = echarts.init(chartDom);
      
      // 准备数据
      const courseNames = this.scores.map(item => item.courseName);
      const scores = this.scores.map(item => item.score);
      
      // 计算平均分
      const avgScore = scores.reduce((sum, score) => sum + score, 0) / scores.length;
      
      const option = {
        title: {
          text: '各科目成绩',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        legend: {
          data: ['分数'],
          left: 'right'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: courseNames,
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '分数',
          max: 100
        },
        series: [
          {
            name: '分数',
            type: 'bar',
            data: scores.map((score, index) => ({
              value: score,
              itemStyle: {
                color: score >= 90 ? '#4CAF50' : 
                       score >= 80 ? '#2196F3' :
                       score >= 70 ? '#FF9800' :
                       score >= 60 ? '#FFC107' : '#F44336'
              }
            }))
          },
          {
            name: '平均分',
            type: 'line',
            data: Array(scores.length).fill(avgScore),
            markLine: {
              data: [{ type: 'average', name: '平均分' }],
              lineStyle: {
                color: '#E91E63',
                type: 'dashed'
              },
              label: {
                formatter: `平均分: ${avgScore.toFixed(1)}`
              }
            },
            symbol: 'none'
          }
        ]
      };
      
      option && myChart.setOption(option);
      
      // 响应式调整
      window.addEventListener('resize', () => {
        myChart.resize();
      });
    },
    
    // 过滤出勤记录
    filterAttendanceRecords() {
      if (!this.selectedCourse) {
        // 如果选择"全部课程"，则显示所有记录
        this.filteredAttendanceRecords = this.paginateRecords(this.attendanceRecords);
        this.totalAttendanceRecords = this.attendanceRecords.length;
      } else {
        // 根据课程ID过滤记录
        const filtered = this.attendanceRecords.filter(record => record.courseId === this.selectedCourse);
        this.filteredAttendanceRecords = this.paginateRecords(filtered);
        this.totalAttendanceRecords = filtered.length;
      }
      // 重置分页到第一页
      this.currentPage = 1;
    },
    
    // 根据当前页码和页面大小返回分页后的记录
    paginateRecords(records) {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return records.slice(start, end);
    },
    
    // 处理页面大小变化
    handleSizeChange(size) {
      this.pageSize = size;
      this.filterAttendanceRecords();
    },
    
    // 处理当前页变化
    handleCurrentChange(page) {
      this.currentPage = page;
      this.filterAttendanceRecords();
    },
    
    // 返回上一页
    goBack() {
      this.$router.go(-1);
    }
  }
}
</script>

<style scoped>
.mb-4 {
  margin-bottom: 20px;
}
.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
.total-score {
  font-size: 18px;
  font-weight: bold;
  color: #409EFF;
}
</style>